package com.zx.cashiersystem.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.landicorp.android.eptapi.DeviceService;
import com.landicorp.android.eptapi.exception.ReloginException;
import com.landicorp.android.eptapi.exception.RequestException;
import com.landicorp.android.eptapi.exception.ServiceOccupiedException;
import com.landicorp.android.eptapi.exception.UnsupportMultiProcess;
import com.zx.cashiersystem.cashiersystem.R;
import com.zx.cashiersystem.service.ClientSocketService;
import com.zx.cashiersystem.utils.AutoSoftUtils;
import com.zx.cashiersystem.utils.Contants;
import com.zx.cashiersystem.utils.DialogUtils;
import com.zx.cashiersystem.utils.Permission;


/**
 * Created by Administrator on 2017/2/7.
 */

public abstract class BaseActivity extends Activity implements Permission.IRoot{
    private Handler handler = new Handler();
    private boolean isDeviceServiceLogined = false;

    //上下文
    protected Context context;
    private static final String TAG = "BaseActivity";
    protected ProgressDialog progressDialog;
    protected DialogUtils dialogUtils;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        initBroadCast();
        setScreen();
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initView();
        dialogUtils = new DialogUtils(this);
        initProgressDialog();
        initEvent();
        initData();

    }

    /**
     * 设置只能竖屏
     */
    protected void setScreen() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    protected abstract void initView();


    protected abstract void initEvent();

    protected abstract void initData();

    /**
     * 通过 id 获得 String
     *
     * @param stringId
     * @return
     */
    protected String getStrings(int stringId) {
        return Contants.getString(context, stringId);
    }

    /**
     * 关闭当前界面
     *
     * @param view
     */
    public void toFinish(View view) {
        finish();
    }

    /**
     * 点击非EditText，全键盘关闭
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (AutoSoftUtils.isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 权限申请结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            haveRoot(requestCode);
        } else {
            onRequestPermissionsFail(requestCode);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 拥有权限就执行
     *
     * @param requestCode
     */
    @Override
    public void haveRoot(int requestCode) {
        onRequestPermissionsSuccess(requestCode);
    }

    /**
     * 同上，
     *
     * @param requestCode 请求码
     */
    protected void onRequestPermissionsSuccess(int requestCode) {

    }


    protected void onRequestPermissionsFail(int requestCode) {
        Permission.showMissingPermissionDialog(context);
    }

    //合并两个数组，多个权限一快申请
    public String[] copyArray(String[] strings1, String[] strings2) {
        String[] strings = new String[(strings1.length + strings2.length)];
        for (int i = 0; i < 2; i++) {
            if (i == 0) {
                for (int j = 0; j < strings1.length; j++) {
                    strings[j] = strings1[j];
                }
            } else if (i == 1) {
                int n = 0;
                for (int j = strings1.length; j < strings1.length + strings2.length; j++) {
                    strings[j] = strings2[n];
                    n++;
                }
            }

        }
        return strings;
    }

    /**
     * 显示加载框
     */
    protected void initProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(getStrings(R.string.loading));
            progressDialog.setCancelable(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    @Override
    protected void onPause() {
        super.onPause();

    }
    //收到消息执行此方法，子类可重写，处理数据
    public void receiverMessages(String str){

    }
    //创建一个继承BroadcastReceiver的广播监听器；
    class SocketReceiver extends BroadcastReceiver {
        private static final String TAG = "socketReceiver";

        //重写onReceive方法，该方法的实体为，接收到广播后的执行代码；
        @Override
        public void onReceive(Context context, Intent intent) {
            String str = intent.getStringExtra("msg");

            Log.e(TAG, "onReceive: "+str );
            receiverMessages(str);
            Toast.makeText(BaseActivity.this,str,Toast.LENGTH_SHORT).show();

        }
    }

    public void initBroadCast() {
        //实例化过滤器；
        intentFilter = new IntentFilter();
        //添加过滤的Action值；
        intentFilter.addAction(MSG_BROCARSTRECEIVER);

        //实例化广播监听器；
        socketReceiver = new SocketReceiver();

        //将广播监听器和过滤器注册在一起；
        registerReceiver(socketReceiver, intentFilter);

        //每个界面都要必须执行
        Intent intent = new Intent(context, ClientSocketService.class);
        //测试任何界面都可发消息
        if (ClientSocketService.is_running) {
            intent.putExtra("msg", "{\"type\":\"boss_login\",\"content\":\"1\"}");
        }
        startService(intent);
    }

    public static final String MSG_BROCARSTRECEIVER = "com.socket.msg";
    //定义一个过滤器；
    private IntentFilter intentFilter;

    //定义一个广播监听器；
    private SocketReceiver socketReceiver;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (socketReceiver!=null)
            unregisterReceiver(socketReceiver);

    }



    /**
     * Run something on ui thread after milliseconds.
     */
    public void runOnUiThreadDelayed(Runnable r, int delayMillis) {
        handler.postDelayed(r, delayMillis);
    }

    /**
     * To gain control of the device service,
     * you need invoke this method before any device operation.
     */
    public void bindDeviceService() {
        try {
            isDeviceServiceLogined = false;
            DeviceService.login(this);
            isDeviceServiceLogined = true;
        } catch (RequestException e) {
            // Rebind after a few milliseconds,
            // If you want this application keep the right of the device service
			runOnUiThreadDelayed(new Runnable() {
				@Override
				public void run() {
					bindDeviceService();
				}
			}, 300);
            e.printStackTrace();
        } catch (ServiceOccupiedException e) {
            e.printStackTrace();
        } catch (ReloginException e) {
            e.printStackTrace();
        } catch (UnsupportMultiProcess e) {
            e.printStackTrace();
        }
    }

    /**
     * Release the right of using the device.
     */
    public void unbindDeviceService() {
        DeviceService.logout();
        isDeviceServiceLogined = false;
    }

}
